package io.renren.modules.police.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.police.dao.PoliceCaseDao;
import io.renren.modules.police.dto.EChartsDTO;
import io.renren.modules.police.dto.PoliceCaseDTO;
import io.renren.modules.police.dto.PoliceServiceTypeDTO;
import io.renren.modules.police.entity.PoliceCaseEntity;
import io.renren.modules.police.service.PoliceCaseService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 案件信息表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2023-09-02
 */
@Service
public class PoliceCaseServiceImpl extends CrudServiceImpl<PoliceCaseDao, PoliceCaseEntity, PoliceCaseDTO> implements PoliceCaseService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public QueryWrapper<PoliceCaseEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String keyWord = (String)params.get("keyWord");
        String reportType = (String)params.get("reportType");

        QueryWrapper<PoliceCaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        if (StringUtils.isNotBlank(reportType)) {
            wrapper.eq("report_type", reportType);
        }
        if (StringUtils.isNotBlank(keyWord)) {
            List<SysUserDTO> sysUserDTOList = sysUserService.getByRealName(keyWord);
            if (CollectionUtils.isEmpty(sysUserDTOList)) {
                wrapper.like("title", keyWord);
            } else {
                List<Long> collect = sysUserDTOList.stream().map(e -> e.getId()).collect(Collectors.toList());
                wrapper.and(wp -> wp.like("title", keyWord).or().in("report_user_id", collect));
            }
        }
        return wrapper;
    }


    @Override
    public List<PoliceCaseDTO> getPoliceCaseing(Map<String, Object> params) {
        Long userId = SecurityUser.getUserId();
        QueryWrapper<PoliceCaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("report_user_id", userId);
        wrapper.eq("status", 0);
        List<PoliceCaseEntity> entityList = this.baseDao.selectList(wrapper);
        List<PoliceCaseDTO> list = ConvertUtils.sourceToTarget(entityList, PoliceCaseDTO.class);
        list.forEach(e -> {
            if (e.getReportUserId() != null) {
                SysUserDTO sysUserDTO = sysUserService.get(e.getReportUserId());
                e.setReportUserName(sysUserDTO.getRealName());
            }
            if (e.getDisposeUserId() != null) {
                SysUserDTO sysUserDTO = sysUserService.get(e.getDisposeUserId());
                e.setDisposeUserName(sysUserDTO.getRealName());
            }
        });
        return list;
    }

    @Override
    public List<PoliceCaseDTO> getPoliceCased(Map<String, Object> params) {
        Long userId = SecurityUser.getUserId();
        QueryWrapper<PoliceCaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("report_user_id", userId);
        wrapper.eq("status", 1);
        List<PoliceCaseEntity> entityList = this.baseDao.selectList(wrapper);
        List<PoliceCaseDTO> list = ConvertUtils.sourceToTarget(entityList, PoliceCaseDTO.class);
        list.forEach(e -> {
            if (e.getReportUserId() != null) {
                SysUserDTO sysUserDTO = sysUserService.get(e.getReportUserId());
                e.setReportUserName(sysUserDTO.getRealName());
            }
            if (e.getDisposeUserId() != null) {
                SysUserDTO sysUserDTO = sysUserService.get(e.getDisposeUserId());
                e.setDisposeUserName(sysUserDTO.getRealName());
            }
        });
        return list;
    }

    @Override
    public PageData<PoliceCaseDTO> getPage(Map<String, Object> params) {
        PageData<PoliceCaseDTO> page = this.page(params);
        page.getList().forEach(e -> {
            if (e.getReportUserId() != null) {
                SysUserDTO sysUserDTO = sysUserService.get(e.getReportUserId());
                e.setReportUserName(sysUserDTO.getRealName());
            }
            if (e.getDisposeUserId() != null) {
                SysUserDTO sysUserDTO = sysUserService.get(e.getDisposeUserId());
                e.setDisposeUserName(sysUserDTO.getRealName());
            }
        });
        return page;
    }

    @Override
    public PoliceCaseDTO getCaseDetail(Long id) {
        PoliceCaseDTO policeCaseDTO = this.get(id);
        if (StringUtils.isNotBlank(policeCaseDTO.getImgUrlList())) {
            policeCaseDTO.setImgUrlLists(Arrays.asList(policeCaseDTO.getImgUrlList().split(",")));
        }
        SysUserDTO reportUser = sysUserService.get(policeCaseDTO.getReportUserId());
        policeCaseDTO.setReportUserName(reportUser.getRealName());
        if (policeCaseDTO.getDisposeUserId() != null) {
            SysUserDTO disposeUser = sysUserService.get(policeCaseDTO.getDisposeUserId());
            policeCaseDTO.setDisposeUserName(disposeUser.getRealName());
        }
        return policeCaseDTO;
    }

    @Override
    public void updateCase(PoliceCaseDTO dto) {
        Long userId = SecurityUser.getUserId();
        if (dto.getStatus() == 0) {
            dto.setDisposeUserId(userId);
        }
        this.update(dto);
    }

    @Override
    public List<EChartsDTO> queryPoliceCasedPieEcharts(Map<String, Object> params) {
        QueryWrapper<PoliceCaseEntity> wrapper = new QueryWrapper<>();
        wrapper.last("WHERE create_date >= DATE_SUB(NOW(), INTERVAL 2 YEAR)");
        List<PoliceCaseEntity> entityList = this.baseDao.selectList(wrapper);
        // 分组
        Map<Integer, List<PoliceCaseEntity>> jobMap = entityList.stream().collect(Collectors.groupingBy(e -> e.getReportType()));
        List<EChartsDTO> chartsDTOList = new ArrayList<>();
        jobMap.keySet().forEach(e -> {
            List<PoliceCaseEntity> policeCaseEntityList = jobMap.get(e);
            if (CollectionUtils.isNotEmpty(policeCaseEntityList)) {
                EChartsDTO eChartsDTO = new EChartsDTO();
                eChartsDTO.setValue(policeCaseEntityList.size());
                eChartsDTO.setName(e == 0 ? "刑事案件" : "民事案件");
                chartsDTOList.add(eChartsDTO);
            }
        });
        return chartsDTOList;
    }

    @Override
    public List<EChartsDTO> queryPoliceCasedBarEcharts(Map<String, Object> params) {
        long now = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String nowYear = simpleDateFormat.format(new Date(now));
        QueryWrapper<PoliceCaseEntity> wrapper = new QueryWrapper<>();
        wrapper.like("create_date", nowYear);
        List<PoliceCaseEntity> entityList = this.baseDao.selectList(wrapper);

        List<EChartsDTO> chartsDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(entityList)) {
            SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
            for (int i = 1; i <= 12; i++) {
                Integer a = i;
                List<PoliceCaseEntity> collect = entityList.stream().filter(e -> Integer.valueOf(monthFormat.format(e.getCreateDate())) == a).collect(Collectors.toList());
                EChartsDTO eChartsDTO = new EChartsDTO();
                eChartsDTO.setName(a + "月");
                eChartsDTO.setValue(collect.size());
                chartsDTOList.add(eChartsDTO);
            }
        }
        return chartsDTOList;
    }
}